<template>
  <el-dialog
    :title="`批量导入${{device: '设备用户', oldman: '老人用户'}[userType]}`"
    :visible.sync="visible"
    width="400px"
  >
    <el-button @click="onDownloadTemplateClick">下载模板</el-button>
    <el-upload
      ref="upload"
      :action="{device: '/api/device/importDevice', oldman: '/api/user/importOldman'}[userType]"
      :auto-upload="false"
      :limit="1"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      :on-success="onSuccess"
      style="margin-top: 16px"
    >
      <el-button slot="trigger" type="primary" plain>选取文件</el-button>
    </el-upload>
    <span slot="footer">
      <el-button type="primary" @click="onSubmit" :loading="submitting">提交</el-button>
      <el-button type="default" @click="visible = false">取消</el-button>
    </span>
  </el-dialog>
</template>


<script>
import Vue from 'vue';

export default {
  data() {
    return {
      visible: false,
      submitting: false,
      userType: null,
    };
  },
  methods: {
    show(options) {
      this.visible = true;
      this.options = options;
      this.userType = options.userType;
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    },
    onDownloadTemplateClick() {
      location.href = `/res/user/${this.userType}_users_template.xls`;
    },
    onChange(file) {
      this.file = file;
    },
    onSubmit() {
      this.submitting = true;
      this.$refs.upload.submit();
    },
    onSuccess(ret) {
      this.submitting = false;
      if (ret.success) {
        const { userReadCount, userAddSuccessCount } = ret.data;
        if (userReadCount == 0) {
          this.$message.error('导入失败：未读取到用户数据，请检查文件内容');
          this.$refs.upload.clearFiles();
        } else if (userReadCount && userReadCount == userAddSuccessCount) {
          this.$message.success('导入成功');
          this.visible = false;
        } else {
          this.visible = false;
          import('./UserImportResultDialog').then(c => {
            c = new Vue(c.default);
            this.$el.parentElement.appendChild(c.$mount().$el);
            c.show(ret.data);
          });
        }
        
        if (userAddSuccessCount) {
          this.options.table.reloadCurrentPage();
        }
      } else {
        this.$message.error(ret.message);
      }
    }
  }
}

</script>
